package com.hava.homework.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.weaver.patterns.ExactAnnotationFieldTypePattern;
import org.springframework.stereotype.Component;

/**
 * Created by yanfa on 2016/10/16.
 */
@Aspect
@Component
public class ServiceLoggingAspect {

//    @After("com.hava.homework.aspect.ServiceLoggingAspect.arithmetic()")
//    public void doServiceLog(JoinPoint joinPoint)
//    {
//        this.printInfo(joinPoint);
//    }

    @AfterThrowing(value = "com.hava.homework.aspect.ServiceLoggingAspect.arithmetic()", throwing="ex")
    public void doThrow(JoinPoint joinPoint,Exception ex){
        System.out.println("Throwing");
        this.printInfo(joinPoint,null,ex);
    }

    @AfterReturning(pointcut="com.hava.homework.aspect.ServiceLoggingAspect.arithmetic()", returning="returnValue")
    public void doReturn(JoinPoint joinPoint,Object returnValue){
        System.out.println("Returning");
        this.printInfo(joinPoint,returnValue,null);
    }

    @Pointcut("execution(* com.hava.homework.service.*.*(..))")
    public void arithmetic(){

    }

    private void printInfo(JoinPoint joinPoint,Object returnValue,Exception ex){
        String method_name = joinPoint.getSignature().getName();
        System.out.println("Class ServiceLoggingAspect " + "[method.name]:" + method_name );
        Object [] args = joinPoint.getArgs();
        for(Object arg : args)
            System.out.println("Class ServiceLoggingAspect " + "    [type]: " + arg.getClass().getTypeName() + "\t[value]: " + arg);

        if(returnValue != null)
            System.out.println("Class ServiceLoggingAspect " + "[event]: normal return" );
        if(ex != null)
            System.out.println("Class ServiceLoggingAspect " + "[event]: throw exception");
    }
}
